package org.dromara.netbar.controller;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.utils.AssertUtils;
import org.dromara.netbar.domain.bo.NetbarCouponMemberBo;
import org.dromara.netbar.domain.bo.NetbarMemberCouponAddBo;
import org.dromara.netbar.domain.bo.NetbarMemberGiftAddBo;
import org.dromara.netbar.domain.vo.NetbarCouponVo;
import org.dromara.netbar.domain.vo.NetbarGiftPackItemVo;
import org.dromara.netbar.service.impl.CouponService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.netbar.domain.vo.NetbarGiftPackVo;
import org.dromara.netbar.domain.bo.NetbarGiftPackBo;
import org.dromara.netbar.service.INetbarGiftPackService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 礼包管理
 *
 * @author Lion Li
 * @date 2025-07-10
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/netbar/giftPack")
public class NetbarGiftPackController extends BaseController {

    private final INetbarGiftPackService netbarGiftPackService;
    private final CouponService couponService;

    /**
     * 查询礼包管理列表
     */
    @SaCheckPermission("netbar:giftPack:list")
    @GetMapping("/list")
    public TableDataInfo<NetbarGiftPackVo> list(NetbarGiftPackBo bo, PageQuery pageQuery) {
        return netbarGiftPackService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出礼包管理列表
     */
    @SaCheckPermission("netbar:giftPack:export")
    @Log(title = "礼包管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(NetbarGiftPackBo bo, HttpServletResponse response) {
        List<NetbarGiftPackVo> list = netbarGiftPackService.queryList(bo);
        ExcelUtil.exportExcel(list, "礼包管理", NetbarGiftPackVo.class, response);
    }

    /**
     * 获取礼包管理详细信息
     *
     * @param packId 主键
     */
    @SaCheckPermission("netbar:giftPack:query")
    @GetMapping("/{packId}")
    public R<NetbarGiftPackVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long packId) {
        return R.ok(netbarGiftPackService.queryById(packId));
    }

    /**
     * 新增礼包管理
     */
    @SaCheckPermission("netbar:giftPack:add")
    @Log(title = "礼包管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody NetbarGiftPackBo bo) {
        return toAjax(netbarGiftPackService.insertByBo(bo));
    }

    /**
     * 修改礼包管理
     */
    @SaCheckPermission("netbar:giftPack:edit")
    @Log(title = "礼包管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody NetbarGiftPackBo bo) {
        return toAjax(netbarGiftPackService.updateByBo(bo));
    }

    /**
     * 删除礼包管理
     *
     * @param packIds 主键串
     */
    @SaCheckPermission("netbar:giftPack:remove")
    @Log(title = "礼包管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{packIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] packIds) {
        return toAjax(netbarGiftPackService.deleteWithValidByIds(List.of(packIds), true));
    }

    /**
     * 获取礼包管理列表（精简数据，用作下拉选）
     */
    @GetMapping("/listNameAndId")
    public R<List<NetbarGiftPackVo>> listNameAndId() {
        return R.ok(netbarGiftPackService.listPackNameAndId());
    }

    // 发礼包
    @SaCheckPermission("netbar:couponMember:add")
    @Log(title = "礼包管理-派发", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/batchGrant")
    public R<Void> addMemberCoupon(@RequestBody NetbarMemberGiftAddBo bos) {
        AssertUtils.notNull(bos, "请选择卡券");
        AssertUtils.hasSize(bos.getMemberIds(), "请选择会员");
        AssertUtils.hasSize(bos.getGiftPackBoList(), "请选择礼包");
        List<NetbarGiftPackVo> netbarCouponVos = netbarGiftPackService.listPackNameAndId();
        Map<Long, Long> couponIdMap = new HashMap<>();
        for (NetbarGiftPackBo netbarGiftPackBo : bos.getGiftPackBoList()) {
            Optional<NetbarGiftPackVo> any = netbarCouponVos.stream().filter(c -> c.getPackId().equals(netbarGiftPackBo.getPackId())).findAny();
            if (any.isPresent()) {
                for (NetbarGiftPackItemVo netbarGiftPackItemVo : any.get().getGiftPackItemList()) {
                    Long count = couponIdMap.getOrDefault(netbarGiftPackItemVo.getCouponId(), 0L);
                    count+= (netbarGiftPackItemVo.getCouponCount() * netbarGiftPackBo.getQuantity());
                    couponIdMap.put(netbarGiftPackItemVo.getCouponId(), count);
                }
            }
        }
        // 调用分发卡券方法
        couponService.sendCoupon(couponIdMap, bos.getMemberIds());
        return R.ok();
    }
}
